<?php
class TwModelPair extends TwModelMulti {
	public $sub_key = '';
	public $num_key = 'num';

	public $config = array ();
	public function __construct($id = 0, $opt = 0) {
		return parent :: __construct($id, $opt);
	}
	/*
	public function setConfig($config)
	{
		$this->config=$config;
	}
	*/
	protected function getDataByDatabase() {
		$data = parent :: getDataByDatabase();
		$ret = array ();
		foreach ($data as $row) {
			$key = $row[$this->sub_key];
			$num = $row[$this->num_key];
			$ret[$key] = $this->config[$key];
			$ret[$key][$this->num_key] = $num;
		}
		return $ret;
	}
	protected function setDataToDatabase($data) {
		foreach ($data as $key => $value) {
			if(isset( $this->init_data[$key][$this->num_key])){
				if ($value[$this->num_key] == $this->init_data[$key][$this->num_key]) {
					continue;
				}
			}
			$value = array (
				$this->sub_key => $key,
				$this->num_key => $value[$this->num_key]
			);
			$this->_replaceData($value, $this->real_table_name, $this->id, $this->table_prikey);
			$this->init_data=$this->data;
		}
	}
	protected function getDataByCache() {
		$data = parent :: getDataByCache();
		if (false===$data){return false;}
		$newdata = array ();
		foreach ($data as $key => $value) {
			$newdata[$key] = $this->config[$key];
			$newdata[$key][$this->num_key] = $value;
		}
		return $newdata;
	}
	protected function setDataToCache($data) {
		$newdata = array ();
		foreach ($data as $key => $value) {
			$newdata[$key] = $value[$this->num_key];
			
		}
		return parent :: setDataToCache($newdata);
	}
	public function add($sub_id,$num,$check=true)
	{
		if($num<=0){return false;}
		if($check && !isset($this->config[$sub_id])){
			return false;
		}
		if(!isset($this->data[$sub_id])){
			$this->data[$sub_id]=$this->config[$sub_id];
			$this->data[$sub_id][$this->num_key]=0;
		}
		$this->data[$sub_id][$this->num_key]+=$num;
		$this->save(true);
		return true;
	}
	public function remove($sub_id,$num,$check=true)
	{
		if($num<=0){return false;}
		
		if($check && !isset($this->config[$sub_id])){
			return false;
		}
		if(!isset($this->data[$sub_id])){
			$this->data[$sub_id]=$this->config[$sub_id];
			$this->data[$sub_id][$this->num_key];
		}
		if($this->data[$sub_id][$this->num_key]<$num){
			return false;
		}
		$this->data[$sub_id][$this->num_key]-=$num;
		
		$this->save(true);
		return true;
	}
	
	public function create() {
		foreach ($this->data as $sub_id => $value) {
			//todo num =1 ?
			$value[$this->table_subkey] = $sub_id;
			$this->_insertData($data_to_insert, $this->real_table_name, $this->id, $this->table_prikey);
		}
		return $this;
	}

}